package me.jessyan.mvparms.demo.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;

import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;


import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.pgyer.pgyersdk.PgyerSDKManager;
import com.pgyer.pgyersdk.callback.CheckoutCallBack;
import com.pgyer.pgyersdk.model.CheckSoftModel;
import com.platform.ai.control.R;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

import me.jessyan.mvparms.demo.di.component.DaggerCommonComponent;
import me.jessyan.mvparms.demo.di.module.CommonModule;
import me.jessyan.mvparms.demo.mvp.contract.CommonContract;
import me.jessyan.mvparms.demo.mvp.model.entity.MessageEvent;
import me.jessyan.mvparms.demo.mvp.model.logic.AllDialogUtil;
import me.jessyan.mvparms.demo.mvp.model.logic.TextUtil;
import me.jessyan.mvparms.demo.mvp.model.logic.api.OkHttpUtils;
import me.jessyan.mvparms.demo.mvp.presenter.CommonPresenter;
import me.jessyan.mvparms.demo.mvp.ui.fragment.AirFragment;
import me.jessyan.mvparms.demo.mvp.ui.fragment.CurtainFragment;
import me.jessyan.mvparms.demo.mvp.ui.fragment.LightFragment;
import me.jessyan.mvparms.demo.mvp.ui.fragment.MusicFragment;
import me.jessyan.mvparms.demo.mvp.ui.fragment.ServerFragment;
import me.jessyan.mvparms.demo.mvp.ui.fragment.TVFragment;
import me.jessyan.mvparms.demo.mvp.ui.receiver.NetworkChangeReceiver;
import me.jessyan.mvparms.demo.mvp.ui.xunfeisdk.core.SpeechDialogListener;
import me.jessyan.mvparms.demo.mvp.ui.xunfeisdk.xunfei.XunFeiSpeechDialogWrap;
import me.jessyan.mvparms.demo.util.TimeThread;
import me.jessyan.mvparms.demo.util.UpdateApkUtil;


import static com.jess.arms.utils.Preconditions.checkNotNull;

import java.io.File;

/**
 * 主窗体
 */
public class MainActivity extends BaseActivity<CommonPresenter> implements CommonContract.View, NetworkChangeReceiver.NetStateChangeObserver {

    @BindView(R.id.title)
    View mTitle;

    @BindView(R.id.tabhost)
    FragmentTabHost mTabHost;

    @BindView(R.id.realtabcontent)
    FrameLayout mFrameLayout;

    @BindView(R.id.tabcontent)
    FrameLayout mTabContent;

    @BindView(R.id.status)
    TextView mStatus;

    @BindView(R.id.iv_wifi)
    ImageView mWifi;

    @BindView(R.id.iv_bluetooth)
    ImageView mBlueTooth;

    @BindView(R.id.tv_time)
    TextView mTime;
    public static String MUSIC_LABEL = "生僻字";
    public static String MUSIC_URL = "";
    BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();

    // 定义数组来存放Fragment界面
    private Class fragmentArray[] = { LightFragment.class, CurtainFragment.class, TVFragment.class, AirFragment.class, MusicFragment.class, ServerFragment.class};

    private int mImageViewArray[] = { R.mipmap.light_unselect, R.mipmap.curtain_unselect,R.mipmap.tv_unselect,R.mipmap.air_unselect,R.mipmap.music_unselect,R.mipmap.server_unselect };

    private int mSelectImageViewArray[] = { R.mipmap.light_select, R.mipmap.curtain_select,R.mipmap.tv_select,R.mipmap.air_select,R.mipmap.music_select,R.mipmap.server_select};
    // 定义一个布局
    private LayoutInflater layoutInflater;
    private Context mContext = this;
    private String[] mTitles;
    private static final int REQUEST_CODE=1231;
    XunFeiSpeechDialogWrap xunfei = new XunFeiSpeechDialogWrap(this);
    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerCommonComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .commonModule(new CommonModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        //Bugtags.start("b7b9228c401727ef24e6d9337b274a47", getApplication(), Bugtags.BTGInvocationEventBubble);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //无title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        return R.layout.activity_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    Handler mHandler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 100:
                    if(!TextUtil.isEmpty(MainActivity.MUSIC_LABEL) && !TextUtil.isEmpty(MUSIC_URL)){
                        mTabHost.setCurrentTab(4);
                        EventBus.getDefault().post(new MessageEvent("update"));
                    }
                    break;
                case 101:
                    mTabHost.setCurrentTab(2);
                    String request = msg.getData().getString("result","打开电视");
                    EventBus.getDefault().post(new MessageEvent(request));
                    break;
                case 200:
                    String id = msg.getData().getString("id","");
                    if(!TextUtil.isEmpty(id)) {
                        new OkHttpUtils().getSyn("http://49.233.50.221:4000/song/url?id=" + id, new OkHttpUtils.OkHttpCallBackListener() {

                            @Override
                            public void onSuccess(String result) {
                                try {
                                    JSONObject jsonObject = new JSONObject(result);
                                    JSONArray jsonData = jsonObject.getJSONArray("data");
                                    String musicUrl = "";
                                    if (jsonData != null && jsonData.length() > 0) {
                                        musicUrl = jsonData.getJSONObject(0).getString("url");
                                        if (!TextUtil.isEmpty(musicUrl)) {
                                            MainActivity.MUSIC_URL = musicUrl;
                                        }
                                    }
                                    mHandler.sendEmptyMessage(100);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFail(String result) {

                            }
                        });
                    }
                    break;
            }
        }
    };

    @Override
    public void initData(Bundle savedInstanceState) {
        TimeThread timeThread = new TimeThread(mTime);//tvDate 是显示时间的控件TextView
        timeThread.start();//启动线程
        PgyerSDKManager.checkVersionUpdate(this, new CheckoutCallBack() {
            @Override
            public void onNewVersionExist(CheckSoftModel checkSoftModel) {
                //得到安装包的下载路径
                new UpdateApkUtil().updateApkDialog(mContext,checkSoftModel.getBuildVersion(),checkSoftModel.getDownloadURL());
            }

            @Override
            public void onNonentityVersionExist(String s) {

            }

            @Override
            public void onFail(String s) {

            }
        });
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},REQUEST_CODE);
        }else{
            xunfei.wakeUpInit(this,mHandler);
        }
        mTabHost.setCurrentTab(0);
        mTitles = getResources().getStringArray(R.array.home_array);
        // 实例化TabHost对象，得到TabHost;
        layoutInflater = LayoutInflater.from(this);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        // 得到fragment的个数
        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            // 为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTitles[i])
                    .setIndicator(getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
                @Override
                public void onTabChanged(String tabId) {
                    int position = 0;
                    switch(tabId){
                        case "灯光":position = 0;break;
                        case "窗帘":position = 1;break;
                        case "电视":position = 2;break;
                        case "空调":position = 3;break;
                        case "音乐":position = 4;break;
                        case "服务":position = 5;break;
                    }
                    for(int i = 0;i < count;i ++) {
                        if(i == position) {
                            ((ImageView) mTabHost.getTabWidget().getChildAt(position).findViewById(R.id.tabimage)).setImageResource(mSelectImageViewArray[position]);
                            ((TextView) mTabHost.getTabWidget().getChildAt(position).findViewById(R.id.textview)).setTextColor(Color.parseColor("#50C0FF"));
                        }else{
                            ((ImageView) mTabHost.getTabWidget().getChildAt(i).findViewById(R.id.tabimage)).setImageResource(mImageViewArray[i]);
                            ((TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(R.id.textview)).setTextColor(Color.parseColor("#333333"));
                        }
                    }
                }

            });

        }

        NetworkChangeReceiver.registerObserver(this);
        NetworkChangeReceiver.registerReceiver(this);
    }



    @Override
    public void showLoading() {

    }



    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        if (!message.isEmpty()) {
            Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    // 2017年12月6日10:37:54    // 增加app的双击退出功能  ZhaoXingHai
    private long mPressedTime = 0;

    @Override
    public void onBackPressed() {
        long mNowTime = System.currentTimeMillis();//获取第一次按键时间
        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mPressedTime = mNowTime;
        } else {//退出程序
            this.finish();
            System.exit(0);
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onResume() {
        super.onResume();
        //注：回调 1
        if(blueadapter != null){
            if(blueadapter.isEnabled()){
                isOpenBluetooth = true;
                mBlueTooth.setImageResource(R.mipmap.icon_bluetooth_white);
            }else{
                isOpenBluetooth = false;
                mBlueTooth.setImageResource(R.mipmap.icon_bluetooth_gray);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注：回调 2

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        return super.dispatchTouchEvent(event);
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        EventBus.getDefault().unregister(this);
    }


    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);
        ImageView imageview = (ImageView) view.findViewById(R.id.tabimage);
        TextView textview = (TextView) view.findViewById(R.id.textview);
        textview.setText(mTitles[index]);
        if(index == 0){
            imageview.setImageResource(mSelectImageViewArray[0]);
            textview.setTextColor(Color.parseColor("#FF5403"));
        }else {
            imageview.setImageResource(mImageViewArray[index]);
            textview.setTextColor(Color.parseColor("#333333"));
        }
        return view;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkChangeReceiver.unRegisterObserver(this);
        NetworkChangeReceiver.unRegisterReceiver(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            boolean success = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
                    success = false;
                    break;
                }
            }
            if (success) {
                xunfei.wakeUpInit(this,mHandler);

            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_CODE);
            }

        }
    }

    @OnClick(R.id.volume)
    public void openVolume(){
        AllDialogUtil.getInstance().showVolumePopWindow(this,mTitle);
    }

    @OnClick(R.id.speech)
    public void openSpeech(){
        xunfei.initDialog(this,mHandler);
    }

    @OnClick(R.id.wifi)
    public void openWifi(){
        ArmsUtils.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));;
//        ArmsUtils.startActivity(WIFIActivity.class);
    }

    @OnClick(R.id.pm25)
    public void openPM25(){
        ArmsUtils.startActivity(FreshAirActivity.class);
    }


    boolean isOpenBluetooth;
    @SuppressLint("MissingPermission")
    @OnClick(R.id.bluetooth)
    public void openBlueTooth(){
        if(isOpenBluetooth){
            mBlueTooth.setImageResource(R.mipmap.icon_bluetooth_gray);
            blueadapter.disable();
        }else{
            mBlueTooth.setImageResource(R.mipmap.icon_bluetooth_white);
            blueadapter.enable();
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onDisconnect() {
        mWifi.setImageResource(R.mipmap.icon_wifi_gray);
        if(blueadapter != null){
            if(blueadapter.isEnabled()){
                isOpenBluetooth = true;
                mStatus.setText("WIFI未连接,蓝牙已开启");
            }else{
                isOpenBluetooth = false;
                mStatus.setText("WIFI未连接,蓝牙未开启");
            }
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMobileConnect() {
        if(blueadapter != null){
            if(blueadapter.isEnabled()){
                mStatus.setText("移动网络已连接,蓝牙已开启");
                isOpenBluetooth = true;
            }else{
                mStatus.setText("移动网络已连接,蓝牙未开启");
                isOpenBluetooth = false;
            }
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onWifiConnect() {
        mWifi.setImageResource(R.mipmap.icon_wifi_white);
        if(blueadapter != null){
            if(blueadapter.isEnabled()){
                mStatus.setText("WIFI已连接,蓝牙已开启");
                isOpenBluetooth = true;
            }else{
                mStatus.setText("WIFI已连接,蓝牙未开启");
                isOpenBluetooth = false;
            }
        }
    }


}
